package com.yundasys.lab13mybatisplus.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @PACKAGE_NAME: com.yundasys.lab13mybatisplus.algorithm
 * @NAME: OrderShardingAlgorithm
 * @USER: jiangta
 * @DATE: 2022/2/21
 * @TIME: 4:19 下午
 * @PROJECT_NAME: springboot-labs
 */
public class OrderRangeShardingAlgorithm implements RangeShardingAlgorithm<Integer> {

    private int ModeID=1000;//默认取值范围。如果只设置了>20000没有设置 最大值，此时默认设置一个最大值：最小值+1000。反之设置了最大值，没有设置最小值，就是最大值-1000

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Integer> rangeShardingValue) {
        //order_id 在1-10000时 用t_order0
        //order_id 在100000-时 用t_order1
        Range<Integer> valueRange = rangeShardingValue.getValueRange();//获得输入的查询条件范围
        String slowerEndpoint = String.valueOf(valueRange.hasLowerBound()?valueRange.lowerEndpoint():"");//查询条件下限
        String supperEndpoint = String.valueOf(valueRange.hasUpperBound()?valueRange.upperEndpoint():"");//查询条件上限


        //处理只有下限或上限的范围
        long  lowerEndpoint=0;
        long  lupperEndpoint=0;
        if(!slowerEndpoint.isEmpty()&&!supperEndpoint.isEmpty()) {
            lowerEndpoint= Math.abs(Long.parseLong(slowerEndpoint));
            lupperEndpoint= Math.abs(Long.parseLong(supperEndpoint));
        } else if(slowerEndpoint.isEmpty()&&!supperEndpoint.isEmpty()) {
            lupperEndpoint= Math.abs(Long.parseLong(supperEndpoint));
            lowerEndpoint=lupperEndpoint-ModeID>0?lupperEndpoint-ModeID:0;
        }
        else if(!slowerEndpoint.isEmpty()&&supperEndpoint.isEmpty()) {
            lowerEndpoint= Math.abs(Long.parseLong(slowerEndpoint));
            lupperEndpoint=lowerEndpoint+ModeID;
        }

        Collection<String> collect = new ArrayList<>();


        //逐个读取查询范围slowerEndpoint~lupperEndpoint的值，进行32取余计算，获得对应的表名称
        for (long i = lowerEndpoint; i <= lupperEndpoint; i++) {
            for (String each : collection) {
                if (each.endsWith("_"+i % Integer.valueOf( collection.size()) + "")) {
                    if(!collect.contains(each))
                    {
                        collect.add(each);
                    }
                }
            }
        }
        return collect;
    }
}
